package createThread.sellTiket;

/**
 * @author wang'ji'cheng
 * @date 2025/7/22
 */
public class Cinema extends Thread {

    // 修改后
    private static final Object obj = new Object();

    private static int ticket = 100;

    /* @Override
     public void run() {
         while(true){
             if(ticket<0){
                 System.out.println("卖完了");
                 break;
             }else {
                 try {
                     Thread1.sleep(100);
                 } catch (InterruptedException e) {
                     throw new RuntimeException(e);
                 }
                 ticket--;
                 System.out.println(Thread1.currentThread().getName()+"在卖票,还剩下"+ticket+"张");
             }

         }
     }*/
    @Override
    public void run() {
        while (true) {
            // 对可能有安全问题的代码加锁,多个线程必须使用同一把锁
            //t1进来后，就会把这段代码给锁起来
            synchronized (obj) {
                if(ticket < 0){
                    break;
                }
                else  {
                    try {
                        Thread.sleep(100);
                        //t1休息100毫秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //窗口1正在出售第100张票
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket + "张票");
                    ticket--; //tickets = 99;
                }
            }
            //t1出来了，这段代码的锁就被释放了
        }
    }
}
